package com.tanhua.mongo.api;

import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import com.tanhua.mongo.utils.IdWorker;
import com.tanhua.mongo.utils.PublishTimeLine;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@DubboService
public class MovementApiIpml implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private PublishTimeLine publishTimeLine;

    /**
     * 当前用户发布动态
     *
     * @param movement
     */
    @Override
    public void publishMovements(Movement movement) {
        try {
            //封装数据
            movement.setPid(idWorker.getNextId("movement"));
            movement.setCreated(System.currentTimeMillis());
            //保存数据
            mongoTemplate.save(movement);

            //异步调用方法完成好友时间表的保存
            publishTimeLine.savePublishTimeLine(movement.getUserId(), movement.getId());
        } catch (Exception e) {
            //忽略事务处理
            e.printStackTrace();
        }
    }

    /**
     * 查询当前用户所有动态信息
     *
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findById(Long userId, int page, int pagesize) {

        Criteria criteria = Criteria.where("userId").is(userId);

        Query query = new Query(criteria);

        long count = mongoTemplate.count(query, Movement.class);

        query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));

        List<Movement> movements = mongoTemplate.find(query, Movement.class);

        return new PageResult(page, pagesize, Math.toIntExact(count), movements);
    }

    /**
     * 获取当前用户所有好友动态id
     *
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Movement> findByIdFriendMovementAll(Long userId, int page, int pagesize) {
        //根据好友时间表查询我可以看到的好友动态id
        Query query = Query.query(Criteria.where("friendId").is(userId));

        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);

        //在根据查询到的动态id查询所有好友动态
        List<ObjectId> movementIds = movementTimeLines.stream()
                .map(item -> item.getMovementId())
                .collect(Collectors.toList());

        //根据动态id查询所有动态信息并分页
        Criteria criteria = Criteria.where("id").in(movementIds);

        Query query1 = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));

        List<Movement> movements = mongoTemplate.find(query1, Movement.class);

        return movements;
    }

    /**
     * 随机生成10条动态数据
     *
     * @param pagesize
     * @return
     */
    @Override
    public List<Movement> randomRecommendM(int pagesize) {
        //随机生成10个id,利用dubbo自带的随机查询的API
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class, Aggregation.sample(pagesize));
        //2、调用mongoTemplate方法统计
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        //3.返回所需要的对象数据
        return results.getMappedResults();
    }

    /**
     * 根据pid查询当前用户所有推荐好友的动态
     *
     * @param pidList
     * @return
     */
    @Override
    public List<Movement> findMovementByPid(List<Long> pidList) {
        Query query = Query.query(Criteria.where("pid").in(pidList));

        return mongoTemplate.find(query, Movement.class);
    }

    /**
     * 获取当前动态id的动态
     *
     * @param movementId
     * @return
     */
    @Override
    public Movement findMovement(String movementId) {
        return mongoTemplate.findById(movementId,Movement.class);
    }

}
